package com.example.campuslink.ui.fragment

import android.content.Intent
import android.view.inputmethod.EditorInfo
import androidx.recyclerview.widget.GridLayoutManager
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.example.campuslink.BR
import com.example.campuslink.R
import com.example.campuslink.commen.adpter.MineInvitationAdapter
import com.example.campuslink.commen.dialog.SupportDialog
import com.example.campuslink.commen.dialog.UserZxingDialog
import com.example.campuslink.commen.enums.MineInvitationNowStatusEnum
import com.example.campuslink.commen.tools.putExtraKey
import com.example.campuslink.databinding.FragmentMineBinding
import com.example.campuslink.ui.activity.MainActivity
import com.example.campuslink.viewModel.MineViewModel
import java.lang.ref.WeakReference

class MineFragment : BaseFragment<FragmentMineBinding, MineViewModel>(
    MineViewModel::class.java,
    R.layout.fragment_mine,
    BR.viewModel
) {
    private var activityRef: WeakReference<MainActivity>? = null
    private var number: String = ""
    private var adapter: MineInvitationAdapter? = null
    override fun onClick() {
        mViewDataBinding?.layoutUserInfoSet?.setOnClickListener({
            mViewModel?.jumpUserInfo()
        })

        mViewDataBinding?.tvFenSiLabel?.setOnClickListener({
            mViewModel?.jumpToFansAndAttentionActivity(putExtraKey.FANS.key)
        })
        mViewDataBinding?.tvFenSiCount?.setOnClickListener({
            mViewModel?.jumpToFansAndAttentionActivity(putExtraKey.FANS.key)
        })
        mViewDataBinding?.tvAttentionCount?.setOnClickListener({
            mViewModel?.jumpToFansAndAttentionActivity(putExtraKey.ATTENTION.key)
        })
        mViewDataBinding?.tvAttentionLabel?.setOnClickListener({
            mViewModel?.jumpToFansAndAttentionActivity(putExtraKey.ATTENTION.key)
        })

        mViewDataBinding?.tvCommend?.setOnClickListener({
            mViewModel?.jumpUserInfo()
        })

        mViewDataBinding?.ivShare?.setOnClickListener({
            val textToShare = "我的校园共享平台账号为: ${number} 快点来加我吧"
            val intent = Intent(Intent.ACTION_SEND)
            intent.setType("text/plain")
            intent.putExtra(Intent.EXTRA_TEXT, textToShare)
            startActivity(Intent.createChooser(intent, "分享账号"))
        })

        mViewDataBinding?.layoutUserZxing?.setOnClickListener {
            val userZxingDialog = UserZxingDialog()
            userZxingDialog.show(childFragmentManager, "userZxingDialog")
        }

        mViewDataBinding?.tvHaveLoveCount?.setOnClickListener(
            {
                val supportDialog = SupportDialog()
                supportDialog.show(childFragmentManager, "supportDialog")
            }
        )
        mViewDataBinding?.tvTvHaveLoveLabel?.setOnClickListener(
            {
                val supportDialog = SupportDialog()
                supportDialog.show(childFragmentManager, "supportDialog")
            }
        )
        mViewDataBinding?.ivScan?.setOnClickListener({
            mViewModel?.jumpToScanActivity()
        })
        mViewDataBinding?.ivMenu?.setOnClickListener({
            activityRef?.get()?.openDrawerLayout()
        })
        mViewDataBinding?.rgRadioGroup?.setOnCheckedChangeListener({ group, checkedId ->
            when (checkedId) {
                R.id.rb_release -> {
                    mViewModel?.getPublicInvitationList()
                    mViewModel?.setInvitationType(MineInvitationNowStatusEnum.PUBLIC.name)
                }

                R.id.rb_collection -> {
                    mViewModel?.getCollectionInvitationList()
                    mViewModel?.setInvitationType(MineInvitationNowStatusEnum.COLLECTION.name)
                }

                R.id.rb_look -> {
                    mViewModel?.getLookInvitationList()
                    mViewModel?.setInvitationType(MineInvitationNowStatusEnum.LOOK.name)
                }

            }
        })
        mViewDataBinding?.etSearch?.setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_DONE || actionId == EditorInfo.IME_ACTION_SEND) {
                // 获取输入内容并发送请求
                val question = mViewDataBinding?.etSearch?.text.toString()
                if (question.isNotBlank()) {
                    mViewModel?.getSearchInvitation(
                        mViewModel?.nowInvitationType?.value
                            ?: MineInvitationNowStatusEnum.PUBLIC.name,
                        question
                    )
                }
                true // 表示已处理该事件
            } else {
                false // 未处理其他动作
            }
        }
    }

    override fun onResume() {
        super.onResume()
        mViewModel?.getUserInfo()
        mViewModel?.getFenSiteList()
        mViewModel?.getAttentionInvitationList()
        if (mViewModel?.nowInvitationType?.value == MineInvitationNowStatusEnum.PUBLIC.name) {
            mViewModel?.getPublicInvitationList()
        } else if (mViewModel?.nowInvitationType?.value == MineInvitationNowStatusEnum.COLLECTION.name) {
            mViewModel?.getCollectionInvitationList()
        } else {
            mViewModel?.getLookInvitationList()
        }
    }

    override fun initViews() {
        mViewModel?.userInfo?.observe(this) {
            mViewDataBinding?.tvTelNumber?.text = it?.userNumber
            mViewDataBinding?.tvUserName?.text = it?.userName
            Glide.with(this).load(it?.userAvatar)
                .apply(RequestOptions.circleCropTransform())
                .error(R.drawable.ic_empty)
                .into(mViewDataBinding?.ivUserImg!!)
            if (it?.userIntro == "") {
                mViewDataBinding?.tvCommend?.text = getString(R.string.user_commend)
            } else {
                mViewDataBinding?.tvCommend?.text = it?.userIntro
            }
            if (it?.userGender == "male") {
                Glide.with(this).load(R.drawable.male)
                    .apply(RequestOptions.circleCropTransform())
                    .error(R.drawable.no_sex)
                    .into(mViewDataBinding?.ivUserSex!!)
            } else if (it?.userGender == "woman") {
                Glide.with(this).load(R.drawable.woman)
                    .apply(RequestOptions.circleCropTransform())
                    .error(R.drawable.no_sex)
                    .into(mViewDataBinding?.ivUserSex!!)
            }
            number = it?.userNumber ?: ""
        }
        mViewModel?.attentionInvitationLiveData?.observe(this) {
            mViewDataBinding?.tvAttentionCount?.text = it.size.toString()
        }
        mViewModel?.fenSiteLiveData?.observe(this) {
            mViewDataBinding?.tvFenSiCount?.text = it.size.toString()
        }

        mViewModel?.publicInvitationLiveData?.observe(this) {
            adapter?.setListData(it.reversed())
        }
        mViewModel?.collectionInvitationLiveData?.observe(this) {
            adapter?.setListData(it.reversed())
        }
        mViewModel?.lookInvitationLiveData?.observe(this) {
            adapter?.setListData(it.reversed())
        }
        mViewModel?.searchInvitationLiveData?.observe(this) {
            adapter?.setListData(it.reversed())
        }

        mViewDataBinding?.freshLayout?.setOnRefreshListener {
            if (mViewModel?.nowInvitationType?.value == MineInvitationNowStatusEnum.PUBLIC.name) {
                mViewModel?.getPublicInvitationList()
            } else if (mViewModel?.nowInvitationType?.value == MineInvitationNowStatusEnum.COLLECTION.name) {
                mViewModel?.getCollectionInvitationList()
            } else {
                mViewModel?.getLookInvitationList()
            }
            mViewDataBinding?.freshLayout?.isRefreshing = false
        }
        mViewDataBinding?.rvInvitationShow?.adapter = adapter
        mViewDataBinding?.rvInvitationShow?.layoutManager = GridLayoutManager(requireContext(), 3)

    }

    override fun initData() {
        mViewModel?.context = context ?: return
        mViewModel?.initDB(context ?: return)
//        mViewModel?.getLookInvitationList()
//        mViewModel?.getCollectionInvitationList()
        mViewModel?.getPublicInvitationList()
        mViewModel?.getAttentionInvitationList()
        mViewModel?.getFenSiteList()
        mViewModel?.getUserInfo()
        val activity = parentFragment?.activity ?: activity
        if (activity is MainActivity) {
            activityRef = WeakReference(activity)
        }

        adapter = MineInvitationAdapter(mViewModel!!)
    }
}